package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;

import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee, Long[] ids) {
        //对密码进行加密
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(),employee.getName(),2);
        employee.setPassword(md5Hash.toString());
        //保存之后employee就会有id
        employeeMapper.insert(employee);
        //关联关系
        if(ids!=null&&ids.length>0){
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除关系
        employeeMapper.deleteRelation(employee.getId());

        //关联关系
        if(ids!=null&&ids.length>0){
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listALL() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        // 代表有数据
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {
        if(!StringUtils.hasText(username)){
            throw new LogicException("用户名不能为空");
        }
        if(!StringUtils.hasText(password)){
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username,password);
        if(employee==null){
            throw new LogicException("用户名或密码错误");
        }

        return employee;
    }

    @Override
    public void batchDelete(Long[] ids) {
        if(ids!=null&&ids.length>0){
            employeeMapper.batchDelete(ids);
        }
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public Workbook exportXls() {
        //查询所有员工
        List<Employee> employees = employeeMapper.selectAll();
        //使用poi创建一个excel
        Workbook wb = new HSSFWorkbook();
        //创建excel中的表
        Sheet sheet = wb.createSheet("员工通讯录");
        //创建标题行数据,从0开始
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //每个员工创建一行数据
            row = sheet.createRow(i+1);
            //创建单元格，写入内容到单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读取上传的文件，并且封装为一个Workbook对象
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读第0张sheet表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum(); //5
        //标题行不用读，lastRowNum是代表索引，需要使用=
        for (int i = 1; i <= lastRowNum; i++) {
            //获取每一行数据
            Row row = sheet.getRow(i);
            Employee employee = new Employee();
            /*if(row.getCell(0)==null||row.getCell(0)==null){ //判断空值问题，用户名或邮箱其中一个为空就不再读取
                break;
            }*/
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            //判断单元格格式
            Cell cell = row.getCell(2);
            if(cell.getCellType()==CellType.NUMERIC){ //作为数字单元格读取
                int age = (int) cell.getNumericCellValue();
                /*if(18>age || age>60){
                   throw new LogicException("第"+i+"行数据有问题，年龄的范围在18-60之间");
                }*/
                employee.setAge(age);
            }else{ //作为文本类型单元格读取
                employee.setAge(Integer.valueOf(cell.getStringCellValue()));
            }
            employeeMapper.insert(employee);
//            save(employee,null);

        }
    }

    @Override
    public List<Employee> selectByRoleSn(String[] sns) {
        return employeeMapper.selectByRoleSn(sns);
    }
}
